<template>
  <div class="user-manage">
    <div class="page-header">
      <h2>前端用户管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>
    
    <el-card>
      <template #header>
        <div class="table-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或邮箱"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="userList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="150" />
        <el-table-column prop="bio" label="个人简介" min-width="150" show-overflow-tooltip />
        <el-table-column prop="birthday" label="生日" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.birthday) }}
          </template>
        </el-table-column>
        <el-table-column prop="vipLevel" label="VIP等级" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.vipLevel" :type="getVipLevelType(scope.row.vipLevel.level)">
              {{ scope.row.vipLevel?.name }}
            </el-tag>
            <span v-else class="text-muted">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="vipExpireDate" label="VIP到期时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.vipExpireDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastLogin) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="userDialogTitle"
      width="700px"
    >
      <el-form :model="userForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" required>
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" required>
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item :label="userForm.id ? '新密码' : '密码'">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            :placeholder="userForm.id ? '留空则不修改密码' : '请输入密码'" 
          />
        </el-form-item>
        
        <el-form-item label="个人简介">
          <el-input 
            v-model="userForm.bio" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入个人简介" 
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生日">
              <el-date-picker
                v-model="userForm.birthday"
                type="date"
                placeholder="选择生日"
                style="width: 100%;"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分">
              <el-input-number 
                v-model="userForm.points" 
                :min="0" 
                :max="99999" 
                style="width: 100%;"
                placeholder="请输入积分"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="VIP等级">
              <el-select v-model="userForm.vipLevelId" placeholder="请选择VIP等级" style="width: 100%;">
                <el-option label="无VIP" :value="null" />
                <el-option
                  v-for="vipLevel in vipLevelList"
                  :key="vipLevel.id"
                  :label="vipLevel.name"
                  :value="vipLevel.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="VIP到期时间">
              <el-date-picker
                v-model="userForm.vipExpireDate"
                type="datetime"
                placeholder="选择VIP到期时间"
                style="width: 100%;"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="状态">
          <el-switch v-model="userForm.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userService } from '../../services/userService'
import { vipLevelService } from '../../services/vipLevelService'

const loading = ref(false)
const searchKeyword = ref('')
const userList = ref([])
const userDialogVisible = ref(false)
const userDialogTitle = ref('')
const vipLevelList = ref([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const userForm = ref({
  id: null,
  username: '',
  email: '',
  password: '',
  bio: '',
  birthday: null,
  avatarUrl: '',
  vipLevelId: null,
  vipLevel: null,
  vipExpireDate: null,
  points: 0,
  status: true
})

// VIP等级类型映射
const getVipLevelType = (level) => {
  const levelMap = {
    0: 'info',      // 普通会员
    1: '',          // 白银会员
    2: 'warning',   // 黄金会员
    3: 'success',   // 铂金会员
    4: 'danger'     // 钻石会员
  }
  return levelMap[level] || 'info'
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return '-';
  return new Date(date).toLocaleDateString('zh-CN');
}

// 日期时间格式化
const formatDateTime = (datetime) => {
  if (!datetime) return '-';
  return new Date(datetime).toLocaleString('zh-CN');
}

// 加载用户列表
const loadUserList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current - 1,  // 后端页码从0开始
      size: pagination.size,
      keyword: searchKeyword.value
    }
    
    const response = await userService.getUserList(params)
    const { data } = response
    
    // 后端返回分页对象
    userList.value = data?.content || []
    pagination.total = data?.totalElements || 0
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 加载VIP等级列表
const loadVipLevels = async () => {
  try {
    const response = await vipLevelService.getVipLevelList()
    vipLevelList.value = response.data || []
  } catch (error) {
    console.error('加载VIP等级列表失败:', error)
    ElMessage.error('加载VIP等级列表失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadUserList()
}

const handleReset = () => {
  searchKeyword.value = ''
  pagination.current = 1
  loadUserList()
}



// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadUserList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadUserList()
}

// 打开创建用户对话框
const handleCreate = () => {
  userDialogTitle.value = '新增用户'
  userForm.value = {
    id: null,
    username: '',
    email: '',
    password: '',
    bio: '',
    birthday: null,
    avatarUrl: '',
    vipLevelId: null,
    vipLevel: null,
    vipExpireDate: null,
    points: 0,
    status: true
  }
  userDialogVisible.value = true
}

// 打开编辑用户对话框
const handleEdit = (user) => {
  userDialogTitle.value = '编辑用户'
  userForm.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    password: '',
    bio: user.bio || '',
    birthday: user.birthday,
    avatarUrl: user.avatarUrl || '',
    vipLevelId: user.vipLevel?.id || null,
    vipLevel: user.vipLevel || null,
    vipExpireDate: user.vipExpireDate,
    points: user.points || 0,
    status: user.status
  }
  userDialogVisible.value = true
}

// 提交用户表单
const handleUserSubmit = async () => {
  try {
    if (!userForm.value.username || !userForm.value.email) {
      ElMessage.error('用户名和邮箱不能为空')
      return
    }

    // 如果是创建用户，密码不能为空
    if (!userForm.value.id && !userForm.value.password) {
      ElMessage.error('创建用户时密码不能为空')
      return
    }

    // 构建符合后端DTO结构的数据
    const submitData = {
      username: userForm.value.username,
      email: userForm.value.email,
      password: userForm.value.password || undefined, // 更新时密码可选
      bio: userForm.value.bio || null,
      birthday: userForm.value.birthday || null,
      avatarUrl: userForm.value.avatarUrl || null,
      vipExpireDate: userForm.value.vipExpireDate || null,
      points: userForm.value.points || 0,
      status: userForm.value.status
    }

    // 处理VIP等级：根据选择的VIP等级ID查找对应的VIP等级对象
    if (userForm.value.vipLevelId) {
      // 根据vipLevelId查找对应的VIP等级对象
      const selectedVipLevel = vipLevelList.value.find(vip => vip.id === userForm.value.vipLevelId)
      if (selectedVipLevel) {
        submitData.vipLevel = selectedVipLevel
      }
    } else {
      // 如果没有选择VIP等级，设置为null
      submitData.vipLevel = null
    }

    // 清理空值
    Object.keys(submitData).forEach(key => {
      if (submitData[key] === null || submitData[key] === undefined || submitData[key] === '') {
        delete submitData[key]
      }
    })

    if (userForm.value.id) {
      // 更新用户 - 不传递密码字段，除非用户输入了新密码
      if (!submitData.password) {
        delete submitData.password
      }
    
      console.log('submitData:', submitData)
      await userService.updateUser(userForm.value.id, submitData)
      ElMessage.success('用户更新成功')
    } else {
      // 创建用户
      await userService.createUser(submitData)
      ElMessage.success('用户创建成功')
    }

    userDialogVisible.value = false
    loadUserList()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存用户失败')
  }
}

// 删除用户
const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userService.deleteUser(user.id)
    ElMessage.success('用户删除成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    const action = row.status ? '禁用' : '启用'
    await ElMessageBox.confirm(
      `确定要${action}用户 "${row.username}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API更新用户状态
    await userService.updateUserStatus(row.id, !row.status)
    ElMessage.success(`${action}成功`)
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

// 初始化加载
onMounted(() => {
  loadUserList()
  loadVipLevels()
})
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>